package
{

	import common.loader.BaseLoader;
	import common.loader.Info;
	import common.loader.LoaderManager;
	import common.loader.LoaderType;

	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;

	import globals.Setting;

	[SWF(width="760", height="600", frameRate="24", backgroundColor="#FFFFFF")]

	public class Loading extends Sprite
	{

		private var loadList:Array = [
//			"data.xml",
			"ui.swf", "map.swf", "tower.swf", "effect.swf", "warrior.swf", "icon.swf", "monster.swf"
//			"drum.png",
//			"map.png",
//			"flag.png"
			];
		private static const URL_RESOURCES:String = "resources/";
		private var assetLoader:BaseLoader;

		public function Loading()
		{
			super();

			if(stage != null)
			{
				init();
			}
			else
			{
				addEventListener(Event.ADDED_TO_STAGE, stageListener);
			}
		}

		private function stageListener(event:Event):void
		{
			removeEventListener(Event.ADDED_TO_STAGE, stageListener);
			init();
		}

		private function init():void
		{
			initStage();
			LoaderManager.init();
			loadConfig();
		}

		private function initStage():void
		{
			stage.align = StageAlign.TOP_LEFT;
			stage.scaleMode = StageScaleMode.NO_SCALE;
		}

		private function loadConfig():void
		{
			LoaderManager.add("config.xml", LoaderType.TEXT, configHandler);
		}

		private function configHandler(configStr:String):void
		{
			LoaderManager.add(URL_RESOURCES + "data.xml", LoaderType.TEXT, dataHandler);
		}

		private function dataHandler(xmlString:String):void
		{
			Setting.DATA = XML(xmlString);
			loadUI();
		}

		private function loadUI():void
		{
			loadNext();
		}

		private function loadNext():void
		{
			if(loadList.length > 0)
			{
				var url:String = loadList.shift();

				if(url == "map.swf")
				{
					url = "map/map.swf";
				}
				LoaderManager.add(URL_RESOURCES + url, LoaderType.SWF, assetHandler);
			}
			else
			{
				loadGame();
			}
		}

		private function assetHandler(info:Info):void
		{
			if(info.url == URL_RESOURCES + "map/map.swf")
			{
				Setting.ASSETS[URL_RESOURCES + "map.swf"] = info.domain;
			}
			else
			{
				Setting.ASSETS[info.url] = info.domain;
			}
			loadNext();
		}

		private function loadGame():void
		{
			LoaderManager.add("Game.swf", LoaderType.SWF, gameHandler);
		}

		private function gameHandler(info:Info):void
		{
			var game:* = info.data;
			stage.addChild(game);
			game.start(stage);
			stage.removeChildAt(0);
		}
	}
}